package com.button.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class AccessFilter extends ZuulFilter {

    @Value("${zuul.ignored-path}")
    private String ignoredPath;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_ERROR_FILTER_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        String token = request.getParameter("token");
        // 判断路径是否不需要验证
        if (isIgnore(request.getRequestURI())) {
            return null;
        }
        // token为空或者无效token
        if (token == null) {
            handleLoginException();
        }
        return null;
    }

    private void handleLoginException() {
        RequestContext requestContext = RequestContext.getCurrentContext();
        requestContext.setSendZuulResponse(false);
        requestContext.setResponseStatusCode(400);
        Map<String, Object> ex = new HashMap<>();
        ex.put("code", "000");
        ex.put("msg", "未登录");
        String response = JSON.toJSONString(ex);
        requestContext.setResponseBody(response);
        requestContext.getResponse().setCharacterEncoding("GBK");
    }
    /**
     * 是否忽略url
     */
    private boolean isIgnore(String url) {
        boolean isIgnore = false;
        String[] ignoreUrls = ignoredPath.split(",");
        for (String u : ignoreUrls) {
            if (url.startsWith(u)) {
                isIgnore = true;
                break;
            }
        }
        return isIgnore;
    }
}
